package logic

import (
	"context"
	"fmt"
	"vipshop/cache"
	"vipshop/models"
	"vipshop/pkg"

	"vipshop/vipshoprpc/internal/svc"
	"vipshop/vipshoprpc/vipshoprpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 注册
func (l *RegisterLogic) Register(in *vipshoprpc.RegisterRequest) (*vipshoprpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line

	var user models.User
	models.DB.Debug().Where("account = ?", in.Account).Find(&user)
	if user.ID != 0 {
		return nil, fmt.Errorf("当前账号已注册")
	}

	user = models.User{
		Account:  in.Account,
		Password: pkg.Md5(in.Password),
	}
	models.DB.Debug().Create(&user)

	result, _ := cache.Rdb.Get(l.ctx, "captcha"+in.Account).Result()
	if result != in.Captcha {
		return nil, fmt.Errorf("图形验证码错误")
	}

	s, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Account).Result()
	if s != in.SendSms {
		return nil, fmt.Errorf("短信验证码错误")
	}

	return &vipshoprpc.RegisterResponse{
		UserId: int64(user.ID),
	}, nil
}
